package org.yu.team2023.flashdays.mixin;

import net.minecraft.network.syncher.EntityDataAccessor;
import net.minecraft.network.syncher.SynchedEntityData;
import net.minecraft.server.level.ServerLevel;
import net.minecraft.world.entity.Entity;
import net.minecraft.world.entity.LivingEntity;
import net.minecraft.world.entity.player.Player;
import net.minecraft.world.level.Level;
import org.spongepowered.asm.mixin.Final;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.Shadow;
import org.spongepowered.asm.mixin.injection.At;
import org.spongepowered.asm.mixin.injection.Inject;
import org.spongepowered.asm.mixin.injection.callback.CallbackInfo;
import org.yu.team2023.flashdays.FDConfig;
import org.yu.team2023.flashdays.ModUtil;
import org.yu.team2023.flashdays.net.DamageParticlePackage;

@Mixin(Entity.class)
public abstract class EntityMixin {
    @Shadow
    public abstract Level level();

    @Shadow
    private int remainingFireTicks;

    @Shadow
    public abstract SynchedEntityData getEntityData();

    @Shadow
    @Final
    private static EntityDataAccessor<Integer> DATA_TICKS_FROZEN;

    @Shadow
    public abstract int getTicksFrozen();

    @Inject(
            method = "setRemainingFireTicks",
            at = @At("HEAD")
    )

    private void flashday_injectSetRemainingFireTicks(int pRemainingFireTicks, CallbackInfo ci) {
        if (level().isClientSide || !(flashday_self() instanceof LivingEntity) || remainingFireTicks != 0 || pRemainingFireTicks <= 0)
            return;
        if (flashday_self() instanceof Player player && !player.getAbilities().invulnerable) {
            flshday_sendMsg("msg.Fire");
            return;
        }
        flshday_sendMsg("msg.Fire");
    }

    @Inject(
            method = "setTicksFrozen",
            at = @At("HEAD")
    )
    private void flashday_injectSetTicksFrozen(int pRemainingFireTicks, CallbackInfo ci) {
        if (level().isClientSide || !(flashday_self() instanceof LivingEntity) || getTicksFrozen() != 0 || pRemainingFireTicks == 0)
            return;
        if (flashday_self() instanceof Player player && !player.getAbilities().invulnerable) {
            flshday_sendMsg("msg.Freeze");
            return;
        }
        flshday_sendMsg("msg.Freeze");
    }

    @SuppressWarnings("all")
    private void flshday_sendMsg(String key) {
        if(FDConfig.shouldShowDamage(flashday_self()))
        if (level() instanceof ServerLevel) {
            ModUtil.findAllPlayersNearby(serverPlayer -> {
                var da = DamageParticlePackage.formEntity(flashday_self(), key, key);
                DamageParticlePackage.sendToClient(serverPlayer, da);
            }, flashday_self(), 64);
        }
    }

    private Entity flashday_self() {
        return (Entity) (Object) this;
    }
}
